<?php

namespace App\Http\Middleware;

use App\Models\CensusModel;
use Illuminate\Http\Request;
use Closure;
use Illuminate\Support\Facades\Log;

class RequestLog
{

    public function handle(Request $request, Closure $next,)
    {
        $traceId = md5(time() . mt_rand(1, 1000000));
        // 记录请求信息
        $requestMessage = [
            'url' => $request->path(),
            'method' => $request->method(),
            'ip' => $request->ips(),
            'headers' => $request->header(),
            'params' => $request->all()
        ];
        Log::channel('request')->info("请求信息：", $requestMessage);

        $respone = $next($request);

        $type_unique_identifier = $request->header('Type-Unique-identifier');
        if ($type_unique_identifier) {
            $type_unique_identifier_arr = explode('_',  $type_unique_identifier);
        } else {
            $type_unique_identifier_arr = [];
        }

        $census = new CensusModel();
        $census->type_unique = $type_unique_identifier;
        $census->type = $type_unique_identifier_arr[0] ?? '';
        $census->unique = $type_unique_identifier_arr[1] ?? '';
        $census->user_id = '';
        $census->url = $request->path();
        $census->method = $request->method();
        $census->ip = $request->ips()[0];
        $census->ua = $request->header('user-agent');
        $census->save();

        $responeData = [
            'traceId' => $traceId,
            'respone' => json_decode($respone->getContent(), true) ?? ""
        ];
        Log::channel('request')->info("返回信息：", $responeData);
        return $respone;
    }
}
